package com.ruoyi.web.cp.service.rm;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.ruoyi.web.cp.domain.rm.RmobMerge;
import com.ruoyi.web.mapper.RmobMergeMapper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author xiesm
 * @Description: TODO
 * @date 2025-07-19 16:28
 */
@Service
public class RmobMergeService {

    @Async
    public void saveRmobMerge(List<String> games, String tableName) {
        //2025-07-21 17:00,日职联,福冈黄蜂,京都不死鸟,57436915.1
        //3-3|0.47|110.00|收：-49.440
        if (CollUtil.isEmpty(games)) {
            return;
        }
        RmobMergeService rmobMergeService = SpringUtil.getBean("rmobMergeService", RmobMergeService.class);
        RmobMerge enity = null;
        for (int i = 0; i < games.size(); i++) {
            String str = games.get(i);
            if (str.startsWith("2025")) {
                String[] strs = str.split(",");
                rmobMergeService.saveOrUpdateByGameId(enity, tableName);
                enity = new RmobMerge(strs[4], DateUtil.parse(strs[0], "yyyy-MM-dd HH:mm"));
            } else {
                String[] strs = str.split("\\|");
                if (strs.length < 4) {
                    continue;
                }
                RmobMerge.Detail detail = new RmobMerge.Detail(strs[0], strs[1], strs[2], strs[3].replace("收：", ""));
                enity.getDetails().add(detail);
            }
            if (i == (games.size() - 1)) {
                rmobMergeService.saveOrUpdateByGameId(enity, tableName);
            }
        }
    }

    @Transactional
    public void saveOrUpdateByGameId(RmobMerge entity, String tableName) {
        if (entity == null) {
            return;
        }
        RmobMergeMapper mapper = SpringUtil.getBean("rmobMergeMapper", RmobMergeMapper.class);
        // 1. 查询是否已存在记录
        List<RmobMerge> existing = mapper.selectByGameIdAndDateRangeTable(entity.getGameId(), null, null, tableName);
        if (CollUtil.isEmpty(existing)) {
            mapper.insertToTable(entity, tableName);
        } else {
            mapper.updateByGameIdAndTable(entity, tableName);
        }
    }
}
